package business.util;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class MaxLength extends PlainDocument 
{
	private static final long serialVersionUID = 1L;
	private int maxLength;
	
	public MaxLength(int maxLength)
	{
		super();
		this.maxLength = maxLength;
	}
	
	public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
	{
		int length;
		
		if (str == null)
			return;
		
		if(maxLength <= 0)
		{
			super.insertString(offs, str, a);
			return;			
		}
		
		length = (getLength() + str.length());
		
		if(length <= maxLength)
		{
			super.insertString(offs, str, a);
		}
		else
		{
			if (getLength() == maxLength) return; // nada a fazer
			String newStr = str.substring(0, (maxLength - getLength()));
			
			super.insertString(offs, newStr, a);
		}
	}
}
